package edu.unc.comp410.sharedcode;
import java.sql.*;
import org.apache.log4j.*;

/**
 * ??? May want 2 versions of these routines (esp getConn):
 *   a. catch all Exceptions and stop computation
 *   b. throw Exceptions that result from being unable to
 *      connect to the DB and let caller decide what to do.
 */
public class SQLutilities {
	
		// Data member
	private static Logger log = Logger.getLogger( SQLutilities.class );

	/**
	 * Establish a SQL connection to a mySQL database.
	 * @param name of database to connect to
	 * @return SQL connection
	 */
	public static Connection 
	getConnection( String db, String mach ) 
	throws ClassNotFoundException {
		
			// Constants
		final String USER = "hedlund";
		final String PASSWORD = "joLY44<ky>";
		
		Connection result = null;
		log.debug( "*** GetConnection: Driver registered" );
		try {
			Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
			final String DBREQUEST = 
				"jdbc:mysql://" + mach + ".cs.unc.edu/" + db + 
				"?user=" + USER + "&password=" + PASSWORD;	
			log.debug( "*** GetConnection: DBREQUEST = " + DBREQUEST );
			result = DriverManager.getConnection( DBREQUEST );			
			log.debug( "*** GetConnection: Connection obtained" );	

		//} catch( ClassNotFoundException e ) {
			//System.err.println( e );
			//e.printStackTrace();
		} catch( SQLException e ) {
			System.err.println( e );
			e.printStackTrace();
		} catch( InstantiationException e ) {
			System.err.println( e );
			e.printStackTrace();
		} catch( IllegalAccessException e ) {
			System.err.println( e );
			e.printStackTrace();
		}
		String logMsg = "SQLutilities: getConnection: DB connection established";
		//out.println( logMsg );
		log.warn( logMsg );
		return result;
	} 
	
	/**
	 * Create a SQL statement that can be executed by mySQL.
	 * @param conn = SQL connection to a mySQL DB.
	 * @return SQL statement that can be executed by mySQL.
	 */
	public static Statement
	getStatement( Connection conn ) {
		Statement stmt = null;
		try {
			if( null != conn ) stmt = conn.createStatement();
		} catch (SQLException e) {
			System.err.println( e );
			e.printStackTrace();
		}
		return stmt;
	}
	
} 
